/**********************************************************

     文件名称: trading.c

     项目功能: 模拟交易功能(收银、找零)

     作者: 佳奇

     邮箱: 1374804492@qq.com 

     创建时间: Sat 27 Aug 2022 11:48:42 AM CST

**********************************************************/


#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include "sup_mgr.h"


//	模拟交易进行收银找零功能
void trading(sales_list* s1, com_list* s2, const char* name, const int id)
{	
	time_t t;
	int com_id, num = 0, rmb, index = 1;
	com_list* demo = s2->next;	//	记住链表第一个节点的位置

	s2 = s2->next;

	while(1)
	{
		index = 1;
		system("clear");	
		printf("\n********模拟交易功能********\n");
		if(s2 == NULL)
		{
			printf("\n仓库里已经没有可以售卖的商品啦!\n");
			printf("\n快去进货吧！！！\n");
			printf("按任意键返回:");
			getchar();
			c_buffer();
			return;
		}

		

		printf("\n有如下商品信息:\n");
		while(s2 != NULL)
		{
			printf("\n商品条码:%d   商品名称:%s   商品单价:%d   商品厂家:%s\n", s2->data->barcode, s2->data->com_name, s2->data->unit, s2->data->manu);
			s2 = s2->next;
		}

		printf("\n\n请输入您要购买的商品编号:");
		while(!geshipanduan(scanf("%d", &com_id)));
		
		s2 = demo;	//	将指针指向头节点	否则再次交易会对空指针进行访问 出现段错误
		while(demo != NULL && demo->data->barcode != com_id)	demo = demo->next;
		
		if(demo == NULL)
		{
			fprintf(stderr, "\n没有此商品!\n");
			printf("是否继续交易(y/n):");
			
			c_buffer();
			if(getchar() == 'y')
			{
				system("clear");
				demo = s2;	//	将指针指向头节点 否则再次交易会对空指针进行访问 出现段错误
				c_buffer();
				continue;
			}
			else return;
		}
	
		sales_list* p = (sales_list*) malloc (sizeof(sales_list));
		sales* n = (sales*) malloc (sizeof(sales));
		if(NULL == p || NULL == n)
		{
			perror("malloc error, 交易失败!");
			return;
		}

		printf("\n请输入购买个数:");

		while(!geshipanduan(scanf("%d", &num)));

		//	判断购买个数是否大于库存数
		if(num > demo->data->allow)
		{
			printf("\n很抱歉,没有这么多件库存\n");
			printf("小的马上去进货 客官稍等!\n");
			printf("是否购买其他商品(y/n):");
			index = 0;

			c_buffer();
			if(getchar() == 'y')
			{
				system("clear");
				demo = s2;
				c_buffer();
				continue;
			}else return;

		}
	
		if(index)
		{
			while(1)
			{
				printf("\n请输入您的支付金额:");
				while(!geshipanduan(scanf("%d", &rmb)));

				c_buffer();
				//	判断支付金额是否足够
				if(rmb < num * demo->data->unit)
				{
					printf("\n金额不足支付！您需要支付 %d 元以上的rmb，请重新支付",  num * demo->data->unit);
					printf("是否取消支付直接返回(y/n):");
					if(getchar() == 'y')	return;
				}
				else break;
			}

			printf("\n共 %d 件商品  每件单价: %drmb  收您:%drmb  找零:%drmb", num, demo->data->unit, rmb, rmb - (num * demo->data->unit));
			
			demo->data->allow = demo->data->allow - num;	//	将商品剩余件数进行更改
		
			//	将本次交易信息插入销售记录链表中
			strcpy(n->name, name);
			n->id = id;
			n->bar = demo->data->barcode;
			n->sell_time = time(&t);
			n->total = num * demo->data->unit;
			strcpy(n->note, "无备注");
			p->next = s1->next;
			p->data = n;
			s1->next = p;
			printf("\n购买成功!\n");

			printf("是否继续购买(y/n):");
			if(getchar() != 'y')
				return;
			else	demo = s2;
		}
	}
}




